package com.tedu.egspringbootmvc.controller;


import com.tedu.egspringbootmvc.common.result.JsonResult;
import com.tedu.egspringbootmvc.common.result.StatusCode;
import com.tedu.egspringbootmvc.mapper.UserMapper;
import com.tedu.egspringbootmvc.pojo.dto.UserArticleDTO;
import com.tedu.egspringbootmvc.pojo.dto.UserLoginDTO;
import com.tedu.egspringbootmvc.pojo.entity.Article;
import com.tedu.egspringbootmvc.pojo.vo.ArticleVO;
import com.tedu.egspringbootmvc.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/v1/users")
@Slf4j
@Api(tags = "用户模块")
@Validated
public class UserController {

    @Autowired
    private UserMapper userMapper;
    @PostMapping("/login")
    @ApiOperation("登录功能")
    public JsonResult login(@RequestBody @Validated UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
        log.info("用户登录信息：{}",userLoginDTO);
        UserVO userVO=userMapper.selectByUsernameAndPassword(userLoginDTO);
        log.debug("查询用户信息：{}",userVO);
        if(userVO!=null){
            session.setAttribute("user",userVO);
            return JsonResult.success();
        }
        log.info("用户登录失败");
        return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
    }


    // 发布文章功能
    @PostMapping("/article")
    @ApiOperation("发布文章功能")
    public JsonResult insertArticle(@RequestBody @Validated UserArticleDTO userArticleDTO, @ApiIgnore HttpSession session){
        log.info("Usercontroller.insertArticle 发布文章信息：{}",userArticleDTO);
        UserVO userVO=(UserVO) session.getAttribute("user");
        log.debug("当前用户信息：{}",userVO);
        /*if(userVO==null){
            log.info("用户未登录");
            return new JsonResult(StatusCode.NOT_LOGIN);
        }*/
        Article article=new Article();
        BeanUtils.copyProperties(userArticleDTO, article);
        article.setUserId(userVO.getId());
        log.debug("article:{}",article);
        userMapper.insert(article);
        log.info("发布文章成功");
        return JsonResult.success();
    }

    // 查询指定文章
    @GetMapping("/selectByArticleId")
    @ApiOperation("查询指定文章")
    @ApiImplicitParam(name = "id",value = "文章id",required = true,dataType = "int",example = "1")
    public JsonResult selectByArticleId(@RequestParam @Range(min = 1,max = 100,message = "文章id必须在1-100之间") int id){
        log.info("查询文章信息，文章id：{}",id);
        ArticleVO articleVO =userMapper.selectById(id);
        log.debug("查询文章信息：{}",articleVO);
        return JsonResult.success(articleVO);
    }

}
